package javaapplication1.service.serviceImpl;

import java.util.Date;
import java.util.List;

import javaapplication1.dao.AccountDao;
import javaapplication1.dao.PetDao;
import javaapplication1.dao.PetOwnerDao;
import javaapplication1.dao.PetStoreDao;
import javaapplication1.dao.oracleImpl.AccountDaoOracleImpl;
import javaapplication1.dao.oracleImpl.PetDaoOracleImpl;
import javaapplication1.dao.oracleImpl.PetOwnerDaoOracleImpl;
import javaapplication1.dao.oracleImpl.PetStoreDaoOracleImpl;
import javaapplication1.model.Account;
import javaapplication1.model.Pet;
import javaapplication1.model.PetOwner;
import javaapplication1.model.PetStore;
import javaapplication1.service.PetOwnerService;
import javaapplication1.view.SessionScope;

public class PetOwnerServiceImpl implements PetOwnerService {

	private PetDao petDao = new PetDaoOracleImpl();
	private PetOwnerDao petOwnerDao = new PetOwnerDaoOracleImpl();
	private PetStoreDao petStoreDao = new PetStoreDaoOracleImpl();
	private AccountDao accountDao = new AccountDaoOracleImpl();

	@Override
	public void buy(Pet pet) {
		Account account = new Account(0, 1, pet.getId(), pet.getStoreId(),
				SessionScope.getId(), pet.getPrice(), new Date());
		accountDao.createAccount(account);
		petDao.updatePet(pet.getId(), SessionScope.getId(), 0);

		petOwnerDao.updatePetOwner(SessionScope.getId(),
				SessionScope.getMoney() - pet.getPrice());
		SessionScope.setMoney(SessionScope.getMoney() - pet.getPrice());

		PetStore petStore = petStoreDao.retrievePetStore(pet.getStoreId());
		petStoreDao.updatePetStore(petStore.getId(), petStore.getBalance()
				+ pet.getPrice());
	}

	@Override
	public void sell(Pet pet, int storeId) {
		Account account = new Account(0, 2, pet.getId(), SessionScope.getId(),
				storeId, pet.getPrice(), new Date());
		accountDao.createAccount(account);
		petDao.updatePet(pet.getId(), 0, storeId);

		petOwnerDao.updatePetOwner(SessionScope.getId(),
				SessionScope.getMoney() + pet.getPrice());

		PetStore petStore = petStoreDao.retrievePetStore(storeId);
		petStoreDao.updatePetStore(petStore.getId(), petStore.getBalance()
				- pet.getPrice());
	}

	@Override
	public PetOwner login(String username, String password) {
		PetOwner loginPerOwner = null;
		List<PetOwner> petOwnerList = this.petOwnerDao.retrievePetOwnerAll();
		for (PetOwner perOwner : petOwnerList) {
			if (username.equals(perOwner.getName())
					&& password.equals(perOwner.getPassword())) {
				loginPerOwner = perOwner;
				SessionScope.setId(loginPerOwner.getId());
				SessionScope.setRole(1);
				SessionScope.setUsername(loginPerOwner.getName());
				SessionScope.setPassword(loginPerOwner.getPassword());
				SessionScope.setMoney(loginPerOwner.getMoney());
			}
		}
		return loginPerOwner;
	}

}